<template>
	<view class="warp">

		<view class="chat" @click.stop="cancle">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scroll="scroll"
			 upper-threshold='0'>
				<view :class="messgae.uuid===me.uuid?'msg me':'msg'" v-for="(messgae,index) in messgaes" :key='index'>
					<image :src="messgae.avat" class="avat"></image>
					<text v-if="messgae.type==='text'">{{messgae.msg}}</text>
					<image :src="messgae.msg" mode="aspectFit" v-else-if="messgae.type==='img'" class="img" @click="preView(messgae.msg)"></image>
					<view class="video" v-else-if="messgae.type==='video'" @click="listenVoice(messgae.msg)" :style="'width: '+messgae.duration*0.05+'upx;'">
						<text class="iconfont">&#xe606;</text>
						<text>{{messgae.duration|time}}</text>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="input">
			<image src="../../static/image/voice.png" mode="" v-if="!isVoice" @click="voice"></image>
			<image src="../../static/image/keyBoard.png" mode="" v-else @click="keyBoard"></image>
			<input type="text" v-model="value" :disabled='isVoice' :placeholder="!isVoice?'':'按住说话'" placeholder-class='placeholder-class'
			 :focus='focus' @confirm='submitMsg' @touchstart="touchstart" @touchend="touchend" @touchmove="touchmove" @longpress="longpress" />
			<image src="../../static/image/expression.png" mode="" v-if="!isExpression" @click="expression"></image>
			<image src="../../static/image/keyBoard.png" mode="" v-else @click="keyBoard"></image>
			<image src="../../static/image/moreFunc.png" mode="" @click="moreFunc"></image>
		</view>
		<!-- 表情 -->
		<view class="expression" v-if="isExpression">
			<view class="dots">
				<image src="../../static/image/expression.png" mode="" v-for="(num,index) in 2" :key='index' :class="swiperIndex===index?'active':''"
				 @click="dotsChange(index)"></image>
			</view>
			<swiper class="swiper" :current='swiperIndex' @change='swiperChange'>
				<swiper-item>
					<scroll-view scroll-y="true" style="height: 100%;">
						<view class="scrollY">
							<text v-for="(expression,index) in expressions" :key='index' @click="addExpression(expression)">{{expression}}</text>
						</view>
						<view class="btn">
							<text @click="submitMsg" v-if="value.length>0" class="active">发送</text>
							<text v-else>发送</text>
							<text class="iconfont active" @click="delMsg" v-if="value.length>0">&#xe609;</text>
							<text class="iconfont" v-else>&#xe609;</text>
						</view>
					</scroll-view>
				</swiper-item>
				<swiper-item>
					<scroll-view scroll-y="true" style="height: 100%;">
						<view class="scrollY">
							<text v-for="(expression,index) in expressions" :key='index' @click="addExpression(expression)">{{expression}}</text>
						</view>
						<view class="btn">
							<text @click="submitMsg">发送</text>
							<text class="iconfont" @click="delMsg">&#xe609;</text>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 更多功能 -->
		<view class="moreFunc" v-if="isMoreFunc">
			<swiper class="swiper" :current='swiperIndex2' @change='swiperChange2' :indicator-dots='true'>
				<swiper-item>
					<view class="swiper-item">
						<view class="func" @click="chooseImg">
							<text class="iconfont">&#xe647;</text>
							<text>照片</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe607;</text>
							<text>拍摄</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe7dd;</text>
							<text>视频通话</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe635;</text>
							<text>位置</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe870;</text>
							<text>红包</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe63c;</text>
							<text>转账</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe60a;</text>
							<text>语音输入</text>
						</view>
						<view class="func">
							<text class="iconfont">&#xe630;</text>
							<text>收藏</text>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>

	</view>
</template>

<script>
	import util from '../../utils/index.js'
	export default {
		data() {
			return {
				scrollTop: 0,
				isVoice: false,
				isExpression: false,
				isMoreFunc: false,
				focus: false,
				value: '',
				messgaes: [],
				roomId: '',
				touchstartClientY: 0,
				swiperIndex: 0,
				swiperIndex2: 0,
				expressions: ['😀', '😁', '😂', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚',
					'😇', '😐', '😑', '😶', '😏', '😣', '😥', '😮', '😯', '😪', '😫',
					'😴', '😌', '😛', '😜', '😝', '😒', '😓', '😔', '😕', '😲', '😷', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧',
					'😨', '😬', '😰', '😱', '😳', '😵', '😡', '😠',
					'💪', '👈', '👉', '☝', '👆', '👇', '✌', '✋', '👌', '👍', '👎', '✊', '👊', '👋', '👏', '👐', '✍'
				],
				me: {},
				other: {},
				page: 0,
				recorderManager: null,
				innerAudioContext: null,
				isCancelVoice: false,
				pixelRatio: 2


			}
		},
		filters:{
			time(num){
				return Math.round(num/1000)+"''"
			}
		},
		onLoad(option) {
			this.recorderManager = uni.getRecorderManager();
			this.innerAudioContext = uni.createInnerAudioContext();
			this.innerAudioContext.autoplay = true;
			this.recorderManager.onStop(res=> {
				let{duration,tempFilePath}=res
				if (this.isCancelVoice) {
					// 取消录音
					console.log('取消');
				} else {
					// 结束录音
					util.myUploadFile({
						tempFilePath
					}).then(res=>{
						uni.sendSocketMessage({
							data: JSON.stringify({
								msg: res,
								uuid: this.me.uuid,
								other: this.other.uuid,
								avat: this.me.avat,
								roomId: this.roomId,
								duration,
								type: 'video'
							})
						});
					})
				}
			});
			const {
				pixelRatio
			} = uni.getSystemInfoSync();
			this.pixelRatio = pixelRatio

			let {
				uuid
			} = uni.getStorageSync('user')
			this.uuid = uuid
			if (option.roomId) this.roomId = option.roomId
			util.myRequest({
				url: '/getUserName/list',
				data: {
					uuid: [uuid, option.uuid]
				}
			}).then(res => {
				let other = res.find(item => item.uuid !== uuid)
				let me = res.find(item => item.uuid === uuid)
				this.me = me
				this.other = other
				uni.setNavigationBarTitle({
					title: other.userName
				})
				// 获取聊天记录
				return util.myRequest({
					url: '/getUserChatRecord',
					data: {
						uuid: [uuid, option.uuid],
						roomId: this.roomId,
						page: this.page
					}
				})
			}).then(res => {
				this.messgaes = res
				this.page += 1
			})

		},
		computed: {
			is_open_socket() {
				return this.$store.state.is_open_socket
			}
		},
		onShow() {
			if (!this.is_open_socket) {
				// 进行socket连接
				util.myConnectSocket.call(this)
			}
			// 注：只有连接正常打开中 ，才能正常收到消息
			uni.onSocketMessage(res => {
				let result = JSON.parse(res.data)
				this.messgaes.push(result)
				// 消息滚到最下面
				this.$nextTick(() => {
					this.scrollTop = this.messgaes.length * 9999
				})

				if (!this.roomId) {
					result.roomId && (this.roomId = result.roomId)
				}
			});
		},
		onPullDownRefresh() {
			uni.stopPullDownRefresh()
			this.upper()
		},
		methods: {
			preView(src){
				let urls=this.messgaes.filter(item=>item.type==='img').map(item=>item.msg)
				let current=urls.findIndex(item=>item===src)
				uni.previewImage({
					urls,
					current
				})
			},
			listenVoice(src){
				this.innerAudioContext.src=src
			},
			longpress() {
				if (!this.isVoice) return
				this.recorderManager.start();
			},
			touchstart(e) {
				if (!this.isVoice) return
				this.touchstartClientY = e.touches[0].clientY
			},
			touchend() {
				if (!this.isVoice) return
				this.touchstartClientY = 0
				this.recorderManager.stop();
			},
			touchmove(e) {
				if (!this.isVoice) return
				if (this.touchstartClientY - e.touches[0].clientY > 79 / this.pixelRatio) {
					uni.showToast({
						title: '上滑取消录音'
					})
					this.isCancelVoice = true
				} else {
					uni.hideToast()
					this.isCancelVoice = false
				}
			},
			chooseImg() {
				uni.chooseImage({
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: res => {
						this.uploadFile(res.tempFilePaths, 0)
					}
				});
			},
			uploadFile(arr, i) {
				if (i === arr.length) return
				util.myUploadFile({
					tempFilePath: arr[i]
				}).then(res => {
					uni.sendSocketMessage({
						data: JSON.stringify({
							msg: res,
							uuid: this.me.uuid,
							other: this.other.uuid,
							avat: this.me.avat,
							roomId: this.roomId,
							type: 'img'
						}),
						success: () => {
							this.uploadFile(arr, ++i)
						}
					});
				})
			},
			addExpression(emoji) {
				this.value += emoji
			},
			delMsg() {
				this.value = Array.from(this.value).slice(0, -1).join().replace(/\,/g, '')
			},
			upper() {
				util.myRequest({
					url: '/getUserChatRecord',
					data: {
						uuid: [this.me.uuid],
						roomId: this.roomId,
						page: this.page
					}
				}).then(res => {
					this.messgaes = [...res, ...this.messgaes]
					this.page += 1
				})
			},
			dotsChange(index) {
				this.swiperIndex = index
			},
			scroll(e) {
				this.scrollTop = e.detail.scrollTop
			},
			submitMsg() {
				// 注：只有连接正常打开中 ，才能正常成功发送消息
				uni.sendSocketMessage({
					data: JSON.stringify({
						msg: this.value,
						uuid: this.me.uuid,
						other: this.other.uuid,
						avat: this.me.avat,
						roomId: this.roomId,
						type: 'text'
					}),
					success: () => {
						this.value = ''
					}
				});
			},
			cancle() {
				this.isExpression = false
				this.isMoreFunc = false
				this.focus = false
			},
			swiperChange(e) {
				this.swiperIndex = e.detail.current
			},
			swiperChange2(e) {
				this.swiperIndex2 = e.detail.current
			},
			voice() {
				this.isVoice = true
				this.isExpression = false
				this.isMoreFunc = false
				this.value = ''
			},
			expression() {
				this.isVoice = false
				this.isExpression = true
				this.isMoreFunc = false
				// 消息滚到最下面
				this.scrollTop = this.messgaes.length * 9999
			},
			moreFunc() {
				if (!this.isMoreFunc) {
					this.isVoice = false
					this.isExpression = false
					this.isMoreFunc = true
					// 消息滚到最下面
					this.scrollTop = this.messgaes.length * 9999
				} else {
					this.keyBoard()
				}
			},
			keyBoard() {
				this.isVoice = false
				this.isExpression = false
				this.isMoreFunc = false
				this.focus = true
			}
		}
	}
</script>

<style lang="scss">
	.placeholder-class {
		text-align: center;
	}

	.warp {
		background-color: #ededed;
		display: flex;
		flex-direction: column;
		height: calc(100vh - 44px);

		>.chat {
			max-height: calc(100vh - 44px - 99upx);
			min-height: calc(100vh - 44px - 99upx - 666upx);
			flex: 1;

			.scroll-Y {
				height: 100%;
				padding-top: 20upx;
				box-sizing: border-box;

				.msg {
					margin: 0 150upx 30upx 20upx;
					display: flex;

					>.avat {
						width: 75upx;
						height: 75upx;
						border-radius: 7upx;
					}

					>.img {
						width: 235upx;
						margin: 0 15upx;
					}
					>.video{
						min-width: 150upx;
						max-width: 480upx;
						background-color: #fff;
						font-size: 30upx;
						line-height: 75upx;
						border: 8upx;
						padding-left: 25upx;
						box-sizing: border-box;
						margin: 0 15upx;
						>text:nth-child(1){
							margin-right: 15upx;
						}
					}

					>text {
						font-size: 30upx;
						line-height: 75upx;
						border: 8upx;
						background-color: #fff;
						margin: 0 15upx;
						// flex: 1;
						min-width: 40upx;
						max-width: 480upx;
						word-break: break-all;
						border-radius: 8upx;
						padding: 0 20upx;
					}

					&.me {
						margin: 0 20upx 30upx 150upx;
						flex-direction: row-reverse;

						>text,>.video {
							background-color: #94ed68;
						}
					}
				}
			}
		}

		>.input {
			height: 99upx;
			border-top: 1px solid #ccc;
			background-color: #f6f6f6;
			display: flex;
			justify-content: space-between;
			align-items: center;

			>image {
				width: 50upx;
				height: 50upx;
				margin: 0 15upx;

				&:nth-last-child(1) {
					margin-left: 0;
				}
			}

			>input {
				height: 73upx;
				background-color: #fff;
				border-radius: 5upx;
				font-size: 30upx;
				flex: 1;
			}
		}

		>.expression {
			height: 666upx;
			display: flex;
			flex-direction: column;

			>.dots {
				height: 135upx;
				background-color: #f6f6f6;
				display: flex;
				align-items: center;

				>image {
					width: 50upx;
					height: 50upx;
					padding: 15upx;
					border-radius: 8upx;

					&.active {
						background-color: #fff;
					}
				}
			}

			>.swiper {
				flex: 1;
				background-color: #ececec;

				.btn {
					position: fixed;
					right: 0;
					bottom: 0;
					width: 250upx;
					height: 120upx;

					>text {
						font-size: 35upx;
						color: #999;
						display: inline-block;
						width: 100upx;
						text-align: center;
						line-height: 80upx;
						background-color: #fff;
						border-radius: 5upx;
						float: right;
						margin: 13upx 13upx 0 0;

						&:nth-child(2).active {
							color: #000;
						}

						&:nth-child(1).active {
							color: #fff;
							background-color: #4dae51;
						}

					}


				}

				.scrollY {
					display: flex;
					justify-content: space-around;
					flex-wrap: wrap;
					align-content: space-around;

					>text {
						font-size: 55upx;
						line-height: 85upx;
						margin: 0 17upx;
					}


				}
			}
		}

		.moreFunc {
			border-top: 1px solid #ccc;

			>.swiper {
				height: 435upx;
				background-color: #f6f6f6;
				padding-bottom: 60upx;
				box-sizing: border-box;

				.swiper-item {
					height: 100%;
					display: flex;
					flex-wrap: wrap;
					justify-content: space-around;
					align-content: space-around;

					>.func {
						display: flex;
						width: 120upx;
						height: 150upx;
						flex-direction: column;
						justify-content: space-between;
						text-align: center;
						color: #999;
						font-size: 22upx;
						margin: 0 33upx;

						>text:nth-child(1) {
							background-color: #fff;
							width: 100%;
							line-height: 115upx;
							border-radius: 25upx;
							color: #4c4c4c;
							font-size: 42upx;
						}

					}
				}
			}
		}
	}
</style>
